import md5 from 'js-md5';
import url from 'url'
const secret = 'CAE3AA84D983B94E25B63D8D5CA766B1';
const app_key = 'H9vUQm8nmwn9uNmg2ibRDp0BRm32R2qS';

class ApiInterceptorFactory{
    constructor(req){
        this.req = req;
        this.regexp = new RegExp('/','g');
    }
    async createSign() {
        const param = await this.paraKeySort(this.req.body);
        const fullSignStr = `${secret}${param}${secret}`;
        const finaSign = md5(fullSignStr).toUpperCase();
        if(finaSign === this.req.body.sign){
            return true;
        }
        return false;
    }

    /*
     * @return String : get parameters sort string
     * @param object : this param is parameter by client
     *
     */
    paraKeySort(data){
        const sortKey = Object.keys(data).sort();
        let signStr = '';
        for(let i = 0, len = sortKey.length; i < len; i++){
            if(sortKey[i] !== 'sign' && data[sortKey[i]] !== undefined){
                signStr += `${sortKey[i]}${data[sortKey[i]]}`
            }
        }
        return signStr;
    }
    checkMethod(){
        const uri = this.req.originalUrl;
        const _method = url.parse(uri).pathname.replace(this.regexp,'.');
        if(_method === `.${this.req.body.method}`){
            return true;
        }
        return false;
    }
    cheackAppKey(){
        if(app_key === this.req.body.app_key){
            return true;
        }
        return false;
    }
}

module.exports = ApiInterceptorFactory;